package com.zhq.base;

import android.app.ActivityManager;
import android.content.Context;


import com.zhq.apputil.utils.LogUtil;
import com.zhq.okhttp.cookie.PersistentCookieStore;

import java.util.List;

import androidx.multidex.MultiDexApplication;

/**
 *
 */
public class BaseApplication extends MultiDexApplication {
    private static BaseApplication instance;
    private PersistentCookieStore cookieStore;
    private Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        String curProcess = getProcessName(this, android.os.Process.myPid());
        if (!getPackageName().equals(curProcess)) {
            return;
        }
        init();
    }

    /**
   * 防止创建进程重新初始化了
   * **/
    private String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps != null && !runningApps.isEmpty()) {
            for (ActivityManager.RunningAppProcessInfo processInfo: runningApps) {
                if (processInfo.pid == pid) {
                    return processInfo.processName;
                }
            }
        }
        return null;
    }

    private void init() {
        instance = this;
        mContext = getApplicationContext();
        LogUtil.setDEBUG(false);//关闭日志
        cookieStore = new PersistentCookieStore(this);

    }

    public Context getAppContext() {
        return mContext;
    }

    public static BaseApplication getInstance() {
        if (instance == null) {
            synchronized (BaseApplication.class) {
                if (instance == null) {
                    instance = new BaseApplication();
                }
            }
        }
        return instance;
    }
    //获取持久化的cookie
    public PersistentCookieStore getCookieStore() {
        if (cookieStore == null) {
            synchronized (BaseApplication.class) {
                if (cookieStore == null)
                    cookieStore = new PersistentCookieStore(this);
            }
        }
        return cookieStore;
    }
}


